package com.hugh.lagouserviceemail.comtroller.email.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @Author: Hugh
 * @Date: 2020/7/20
 */
@Component
@Slf4j
public class EmailUtil {

    @Value("${mail.host}")
    private String host;
    @Value("${mail.port}")
    private String port;
    @Value("${mail.nick}")
    private String nick;
    @Value("${mail.username}")
    private String username;
    @Value("${mail.password}")
    private String password;
    @Value("${mail.from}")
    private String from;

    public boolean sendEmail(String title,String content, String toEmail) {
        Properties properties = System.getProperties();

        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", port);
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.starttls.enable", "true");// outlook邮箱需要加上

        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        };

        Session session = Session.getDefaultInstance(properties, authenticator);

        try {
            MimeMessage message = new MimeMessage(session);

            message.setFrom(new InternetAddress(nick + " <"+from +">"));

            /**
             *  设置收件人地址（可以增加多个收件人、抄送、密送），即下面这一行代码书写多行
             * MimeMessage.RecipientType.TO:发送
             * MimeMessage.RecipientType.CC：抄送
             * MimeMessage.RecipientType.BCC：密送
             */
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));


            message.setSubject(title, "UTF-8");
            message.setContent(content, "text/html;charset=UTF-8");

            Transport.send(message);

            log.info("Sent message successfully.... title：" + title);
            return true ;

        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
        return false;
    }
}
